package com.kalvan.commons.db.gateway;

import cn.hutool.core.io.IoUtil;
import com.kalvan.commons.db.DataSourceConstants;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;

/***
 * gateway数据源加载扫描
 *
 * @author kalvan.tools:chenliang
 */
@Configuration
@MapperScan(basePackages = DataSourceConstants.GATEWAY_MAPPER_PACKAGE, sqlSessionFactoryRef = DataSourceConstants.GATEWAY_SESSION_FACTORY)
public class GatewayDataSourceConfig {
    @Value(DataSourceConstants.GATEWAY_SHARDING_YML)
    private String yamlPath;

    @Bean
    public DataSource gatewayDataSource() throws SQLException, IOException {
        return YamlShardingDataSourceFactory
                .createDataSource(IoUtil.readBytes(this.getClass().getResourceAsStream(yamlPath)));
    }

    @Bean
    public SqlSessionFactory gatewaySessionFactory(@Qualifier(DataSourceConstants.GATEWAY_DATA_SOURCE) DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(DataSourceConstants.GATEWAY_MAPPER_PATH));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate gatewaySqlSessionTemplate(
            @Qualifier(DataSourceConstants.GATEWAY_SESSION_FACTORY) SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public DataSourceTransactionManager gatewayTransactionManager(@Qualifier(DataSourceConstants.GATEWAY_DATA_SOURCE) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
